//
//  ZMSearchCollectionView.swift
//  LoveBeen
//
//  Created by pg on 2017/8/9.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

class ZMSearchCollectionView: UICollectionView {

    let flowLayout = ZMSearchCollectionViewFlowLayout()
    
    //数据源数组
    var keyWordsArray: [String]?{
        didSet{
            flowLayout.keyWordsArray = keyWordsArray!
            reloadData()
        }
    }
    
    //缓存搜索历史记录
    var searchHistoryArray: [String]?{
        didSet{
            
        }
    }
    
    //闭包向外传递数据
    var collectionviweCellSelected:((String)->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        self.backgroundColor = UIColor(white: 0.95, alpha: 1)
        delegate = self
        dataSource = self
        setupflowLayout()
    }
    
    //MARK:- 初始化collectionview布局对象  flowlayout
    private func setupflowLayout(){
        
        flowLayout.headerReferenceSize = CGSize(width: 414, height: 100)
        
        
        //注册cell
        register(SearchviewCell.self, forCellWithReuseIdentifier: "cell")
        //注册组头view
        register(SearchViewHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
//collectionview 数据源和代理方法
extension ZMSearchCollectionView: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0{
            return self.keyWordsArray?.count ?? 0
        }
        return self.searchHistoryArray?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        var tempStringgID: String?
        var tempArray: [String]?
        
        if indexPath.section == 0{
            //加载第一组的cell
            tempStringgID = "cell"
            
            //加载第一组的数据源
            tempArray = self.keyWordsArray
            
        }else{
            //加载第二组的cell
            tempStringgID = "cell"
            
            
            
            //加载第二组的数据源
            tempArray = self.searchHistoryArray

        }
        
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: tempStringgID!, for: indexPath) as! SearchviewCell
        
        cell.title = tempArray?[indexPath.row]
        
        
    
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //获取选中cell的text
        let selectedText = self.keyWordsArray![indexPath.row]
        //将选中的text显示再搜索框中
        self.searchHistoryArray?.append(selectedText)
        //使用闭包向外传递cell的点击事件,,传递选中cell对应的text
        collectionviweCellSelected?(selectedText)
        
    }
    
    
    
    //MARK:- 设置collectionview组头视图
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        var headerview = SearchViewHeaderView()
        
        if kind == UICollectionElementKindSectionHeader{
            
            headerview = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! SearchViewHeaderView
            
            if indexPath.section == 0{
                headerview.titleLabel.text = "热门搜索"
            }else{
                headerview.titleLabel.text = "历史记录"
            }
            
        }
        
        return headerview
        
    }
    //MARK:- 设置collectionview组头视图的Size
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        if section == 0 {
            return CGSize(width: UIScreen.main.bounds.width, height: 60)
        }else{
            
            return CGSize(width: UIScreen.main.bounds.width, height: 40)
        }
        
    }
    
    
}

//自定义cell
class SearchviewCell : UICollectionViewCell{
    
    var title: String?{
        didSet{
            
            label.text = title
            
        }
    }
    
    
    fileprivate lazy var  label: UILabel = {
        let lab = UILabel(text: "", fontSize: 16, textColor: UIColor.darkGray)
        
        lab.sizeToFit()
        lab.textAlignment = .center
        return lab
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加label
        
        contentView.addSubview(label)
        
        label.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        //设置在cell的样式
        self.layer.cornerRadius = 15
        self.layer.masksToBounds = true
        
        self.backgroundColor = UIColor(white: 0.98, alpha: 1)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


//自定义组头视图
class SearchViewHeaderView: UICollectionReusableView{
    
    
    //MARK:- 懒加载label
    fileprivate lazy var titleLabel : UILabel = {
       let label = UILabel(text: "热门搜索", fontSize: 14, textColor: UIColor.lightGray)
        
        label.textAlignment = .left
        label.sizeToFit()
        return label
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(self).offset(-5)
            make.leading.equalTo(self).offset(10)
        }
        backgroundColor = UIColor(white: 0.9, alpha: 1)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}









